//
//  MNDMNDInvestmentRecordListViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/12.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDInvestmentRecordListViewController.h"
#import "SYRefreshControl.h"
#import "MNDInvestmentRecordListCell.h"
//#import "UIView+LoadingOrBlank.h"

//UIKIT_EXTERN NSString *const RecordListStyleKey;

@interface MNDInvestmentRecordListViewController () <UITableViewDataSource, UITableViewDelegate>

/*! 加载第几页，为空默认第一页 */
@property (nonatomic) NSInteger perpage;
/*! 每页数据数 */
@property (nonatomic) NSInteger pageSize;

@property (strong, nonatomic) NSMutableArray *tenderList;

//记录列表总条数
@property (nonatomic) NSInteger totalnum;

@property (strong, nonatomic)UIView *placeHolderMaskView;


@end

@implementation MNDInvestmentRecordListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 140.0;
    
    self.perpage = 1; //默认第一页
    self.pageSize = 10; //每页10条数据
    
    self.totalnum = 0; //默认有0条数据
    
    //配置下拉刷新下拉加载更多
    WeakSelf(self);
    [SYRefreshControl configGifMJRefresh:self.tableView
                             refreshType:MJRefreshSupportALl
                            beginRefresh:NO
                         timeLabelHidden:YES
                        stateLabelHidden:YES
                            refreshBlock:^{
                                
                                [weakself refreshDatas];
                                
                            } loadMoreBlock:^{
        
                                [weakself loadMoreDatas];
                            }];
    [self refreshDatas];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goInvestButtonAction:) name:@"goInvestButtonAction" object:nil];
}


- (void)goInvestButtonAction:(NSNotification *)notification {
    self.tabBarController.selectedIndex = 1;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GoTenderActionNotification" object:@1];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshDatas {
    
    if (self.tenderList.count <= 0) {
        [self.view beginLoading];
    }
    self.perpage = 1;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"perpage"      : @(self.perpage),
                                                          @"pagesize"     : @(self.pageSize),
                                                          @"tender_status": @(self.listStyle)}];
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_TENDER_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            NSArray *array = [MNDInvestmentRecordModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"li"]];
            if (array.count > 0) {
                weakself.totalnum = [responseModel.data[@"sum"] integerValue];
            }else {
                
            }
            [weakself.tenderList removeAllObjects];
            [weakself.tenderList addObjectsFromArray:array];
            [weakself.tableView reloadData];
            
            [SYRefreshControl configAfterLoading:weakself.tableView hasData:array.count];
            [weakself.view configBlankPage:SYBlankPageTypeNoData hasData:array.count reloadButtonBlock:nil];
            if(array.count <= 0) {
                weakself.view.blankPageView.investButton.hidden = NO;
            }
            
        } else {
            [weakself.view endLoading];
            [SYRefreshControl configAfterLoading:weakself.tableView hasData:NO];
            NSDictionary *dict = responseModel.msg;
            dict.count > 0? [NetworkProgressHUD showHudMsg:dict[@"error"]] : [NetworkProgressHUD showHudMsg:@"获取数据出错"];
        }
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakself.tableView hasData:NO];
        
        if (weakself.tenderList.count > 0) {
            [NetworkProgressHUD showHudNetworkError:error];
        } else {
            SYBlankPageType blankType = [weakself.view blankPageTypeWithError:error];
            [weakself.view configBlankPage:blankType
                                   hasData:NO
                         reloadButtonBlock:^(id sender) {
                             [weakself refreshDatas];
                         }];
        }
    }];
}

- (void)loadMoreDatas {
    self.perpage ++;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"perpage"      : @(self.perpage),
                                                          @"pagesize"     : @(self.pageSize),
                                                          @"tender_status": @(self.listStyle)}];
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_TENDER_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            NSArray *array = [MNDInvestmentRecordModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"li"]];
            [SYRefreshControl configAfterLoading:weakself.tableView hasData:array.count];
            [weakself.tenderList addObjectsFromArray:array];
            [weakself.tableView reloadData];
            
        } else {
            [SYRefreshControl configAfterLoading:weakself.tableView hasData:NO];
            NSDictionary *dict = responseModel.msg;
            dict.count > 0? [NetworkProgressHUD showHudMsg:dict[@"error"]] : [NetworkProgressHUD showHudMsg:@"获取数据出错"];;
        }
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakself.tableView hasData:NO];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.tenderList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *const cellIdentifier = @"cell";
    
    MNDInvestmentRecordListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    MNDInvestmentRecordModel *model = self.tenderList[indexPath.row];
    [cell configCellWithModel:model];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(recordListDidSelectRowWithModel:)]) {
        MNDInvestmentRecordModel *model = self.tenderList[indexPath.row];
        [self.delegate recordListDidSelectRowWithModel:model];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.delegate && [self.delegate respondsToSelector:@selector(recordListDidScroll:withTotalnum:)]) {
        [self.delegate recordListDidScroll:scrollView withTotalnum:self.totalnum];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Gettter

- (NSMutableArray *)tenderList {
    if (!_tenderList) {
        _tenderList = [NSMutableArray array];
    }
    
    return _tenderList;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
